<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\service\WxService;
use app\service\AliSmsService;


class push extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('push');
        // 设置参数

    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        // $output->writeln('app\command\push');
        echo sprintf("push start: %s\n", date('Y-m-d H:i:s'));
        Db::name('new_user_question_history')
            ->where('rate', '>', 0)
            ->chunk(100, function ($historys) {
                $aliSmsConfig = config('app.ali_sms');
                foreach ($historys as $history) {
                    $now = time();
                    $day = date('Y-m-d', $now - 86400 * $history['rate']);
                    if ($history['result_day'] <= $day) {
                        # 更新订单状态
                        $updateData = [
                            'result_day' => date('Y-m-d', $now),
                        ];
                        $updateRes = Db::name('new_user_question_history')->where(['id' => $history['id']])->update($updateData);
                        if ($updateRes) {
                            echo sprintf("update:%s result_day %s -> %s\n", $history['id'], $history['result_day'], $updateData['result_day']);
                        }
                        //发送短信提醒
                        $args = [
                            'phone' => $history['user_phone'],
                            'template'  => $aliSmsConfig['pushTpl'],
                            'params'    => json_encode([
                                'name' => substr($history['user_phone'], -4) . '用户',
                                'time' => date('Y年m月d日', $now),
                            ], JSON_UNESCAPED_UNICODE),
                        ];
                        $res = AliSmsService::main($args);
                    }
                }
            });

        echo sprintf("push end: %s\n", date('Y-m-d H:i:s'));
    }
}
